<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorate="~{layout/default}">
<head>
    <title>销售任务管理</title>
    <style>
        .task-container {
            display: flex;
            flex-direction: column;
            gap: 20px;
            padding: 20px;
        }
        .task-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .task-filters {
            display: flex;
            gap: 10px;
            padding: 15px;
            background-color: #f8f9fa;
            border-radius: 5px;
        }
        .task-board {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
            gap: 15px;
        }
        .task-column {
            background-color: #f1f3f5;
            border-radius: 5px;
            padding: 10px;
        }
        .task-card {
            background-color: white;
            border-radius: 5px;
            padding: 12px;
            margin-bottom: 10px;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
        }
        .task-card:hover {
            box-shadow: 0 2px 5px rgba(0,0,0,0.2);
        }
        .task-title {
            font-weight: bold;
            margin-bottom: 5px;
        }
        .task-due {
            color: #6c757d;
            font-size: 12px;
        }
        .task-priority {
            display: inline-block;
            padding: 2px 6px;
            border-radius: 3px;
            font-size: 12px;
            margin-right: 5px;
        }
        .high { background-color: #ffcccc; }
        .medium { background-color: #fff2cc; }
        .low { background-color: #e6f7ff; }
        .task-actions {
            margin-top: 10px;
            display: flex;
            justify-content: flex-end;
            gap: 5px;
        }
        button.add-task {
            background-color: #0d6efd;
            color: white;
            border: none;
            padding: 8px 15px;
            border-radius: 4px;
            cursor: pointer;
        }
    </style>
</head>
<body>
    <div layout:fragment="content">
        <div class="task-container">
            <div class="task-header">
                <h2>销售任务</h2>
                <button class="add-task" onclick="showAddTaskModal()">添加任务</button>
            </div>

            <div class="task-filters">
                <select id="filterStatus">
                    <option value="">所有状态</option>
                    <option value="todo">待办</option>
                    <option value="inprogress">进行中</option>
                    <option value="completed">已完成</option>
                </select>
                <select id="filterPriority">
                    <option value="">所有优先级</option>
                    <option value="high">高</option>
                    <option value="medium">中</option>
                    <option value="low">低</option>
                </select>
                <select id="filterAssignee">
                    <option value="">所有负责人</option>
                    <!-- 将动态填充 -->
                </select>
                <button onclick="applyFilters()">应用筛选</button>
                <button onclick="resetFilters()">重置</button>
            </div>

            <div class="task-board">
                <div class="task-column">
                    <h3>待办</h3>
                    <div id="todo-tasks">
                        <!-- 任务将在这里加载 -->
                        <div class="task-card">
                            <div class="task-title">联系ABC公司</div>
                            <div class="task-due">截止日期: 2023年10月15日</div>
                            <span class="task-priority high">高</span>
                            <div>跟进销售机会</div>
                            <div class="task-actions">
                                <button onclick="editTask(1)">编辑</button>
                                <button onclick="moveTask(1, 'inprogress')">开始</button>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="task-column">
                    <h3>进行中</h3>
                    <div id="inprogress-tasks">
                        <!-- 任务将在这里加载 -->
                        <div class="task-card">
                            <div class="task-title">准备XYZ提案</div>
                            <div class="task-due">截止日期: 2023年10月12日</div>
                            <span class="task-priority medium">中</span>
                            <div>为XYZ公司创建销售提案</div>
                            <div class="task-actions">
                                <button onclick="editTask(2)">编辑</button>
                                <button onclick="moveTask(2, 'completed')">完成</button>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="task-column">
                    <h3>已完成</h3>
                    <div id="completed-tasks">
                        <!-- 任务将在这里加载 -->
                        <div class="task-card">
                            <div class="task-title">DEF有限公司演示</div>
                            <div class="task-due">完成日期: 2023年10月5日</div>
                            <span class="task-priority low">低</span>
                            <div>产品演示已完成</div>
                            <div class="task-actions">
                                <button onclick="viewTask(3)">查看</button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 任务模态框（默认隐藏） -->
        <div id="taskModal" style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background-color: rgba(0,0,0,0.5);">
            <div style="background-color: white; margin: 10% auto; padding: 20px; width: 50%; border-radius: 5px;">
                <h3 id="modalTitle">添加任务</h3>
                <form id="taskForm">
                    <div>
                        <label for="taskTitle">标题:</label>
                        <input type="text" id="taskTitle" required style="width: 100%; margin-bottom: 10px; padding: 8px;">
                    </div>
                    <div>
                        <label for="taskDescription">描述:</label>
                        <textarea id="taskDescription" style="width: 100%; margin-bottom: 10px; padding: 8px; height: 80px;"></textarea>
                    </div>
                    <div>
                        <label for="taskDueDate">截止日期:</label>
                        <input type="date" id="taskDueDate" style="margin-bottom: 10px; padding: 8px;">
                    </div>
                    <div>
                        <label for="taskPriority">优先级:</label>
                        <select id="taskPriority" style="margin-bottom: 10px; padding: 8px;">
                            <option value="high">高</option>
                            <option value="medium">中</option>
                            <option value="low">低</option>
                        </select>
                    </div>
                    <div>
                        <label for="taskAssignee">分配给:</label>
                        <select id="taskAssignee" style="margin-bottom: 10px; padding: 8px;">
                            <!-- 将动态填充 -->
                        </select>
                    </div>
                    <div style="display: flex; justify-content: flex-end; gap: 10px; margin-top: 15px;">
                        <button type="button" onclick="closeModal()">取消</button>
                        <button type="submit">保存任务</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <th:block layout:fragment="scripts">
        <script>
            let tasks = []; // 存储任务数据
            
            document.addEventListener('DOMContentLoaded', function() {
                loadTasks();
                loadUsers();
                
                // 设置表单提交事件
                document.getElementById('taskForm').addEventListener('submit', function(e) {
                    e.preventDefault();
                    saveTask();
                });
            });

            // 从服务器加载任务
            function loadTasks() {
                // 获取当前过滤条件
                const status = document.getElementById('filterStatus').value;
                const priority = document.getElementById('filterPriority').value;
                const assignee = document.getElementById('filterAssignee').value;
                
                // 构建API URL，添加过滤参数
                let url = '/crm/api/sales/tasks/list';
                const params = new URLSearchParams();
                if (status) params.append('status', status);
                if (priority) params.append('priority', priority);
                if (assignee) params.append('assigneeId', assignee);
                
                if (params.toString()) {
                    url += '?' + params.toString();
                }
                
                fetch(url)
                    .then(response => response.json())
                    .then(result => {
                        if (result.code === 200) {
                            tasks = result.data;
                            renderTasks();
                        } else {
                            console.error('加载任务失败:', result.message);
                        }
                    })
                    .catch(error => console.error('加载任务失败:', error));
            }
            
            // 渲染任务到看板
            function renderTasks() {
                // 清空任务列表
                document.getElementById('todo-tasks').innerHTML = '';
                document.getElementById('inprogress-tasks').innerHTML = '';
                document.getElementById('completed-tasks').innerHTML = '';
                
                // 对每个任务进行分组渲染
                tasks.forEach(task => {
                    let container;
                    let actionButtons = '';
                    
                    switch(task.status) {
                        case 'todo':
                            container = document.getElementById('todo-tasks');
                            actionButtons = `
                                <button onclick="editTask(${task.id})">编辑</button>
                                <button onclick="moveTask(${task.id}, 'inprogress')">开始</button>
                            `;
                            break;
                        case 'inprogress':
                            container = document.getElementById('inprogress-tasks');
                            actionButtons = `
                                <button onclick="editTask(${task.id})">编辑</button>
                                <button onclick="moveTask(${task.id}, 'completed')">完成</button>
                            `;
                            break;
                        case 'completed':
                            container = document.getElementById('completed-tasks');
                            actionButtons = `<button onclick="viewTask(${task.id})">查看</button>`;
                            break;
                        default:
                            return; // 跳过未知状态
                    }
                    
                    const priorityClass = task.priority.toLowerCase();
                    const priorityLabel = {
                        'high': '高',
                        'medium': '中',
                        'low': '低'
                    }[task.priority.toLowerCase()];
                    
                    const dueDate = new Date(task.dueDate).toLocaleDateString('zh-CN');
                    const taskEl = document.createElement('div');
                    taskEl.className = 'task-card';
                    taskEl.innerHTML = `
                        <div class="task-title">${task.title}</div>
                        <div class="task-due">截止日期: ${dueDate}</div>
                        <span class="task-priority ${priorityClass}">${priorityLabel}</span>
                        <div>${task.description || ''}</div>
                        <div>负责人: ${task.assigneeName || '未分配'}</div>
                        <div class="task-actions">
                            ${actionButtons}
                        </div>
                    `;
                    
                    container.appendChild(taskEl);
                });
            }

            // 加载用户到负责人下拉菜单
            function loadUsers() {
                fetch('/crm/api/sales/team/members')
                    .then(response => response.json())
                    .then(result => {
                        if (result.code === 200) {
                            const users = result.data;
                            const assigneeDropdown = document.getElementById('taskAssignee');
                            const filterAssignee = document.getElementById('filterAssignee');
                            
                            // 清空现有选项
                            assigneeDropdown.innerHTML = '<option value="">选择负责人</option>';
                            filterAssignee.innerHTML = '<option value="">所有负责人</option>';
                            
                            users.forEach(user => {
                                const option = document.createElement('option');
                                option.value = user.id;
                                option.textContent = user.name;
                                
                                assigneeDropdown.appendChild(option.cloneNode(true));
                                filterAssignee.appendChild(option);
                            });
                        } else {
                            console.error('加载用户失败:', result.message);
                        }
                    })
                    .catch(error => console.error('加载用户失败:', error));
            }

            function showAddTaskModal() {
                document.getElementById('modalTitle').textContent = '添加任务';
                document.getElementById('taskForm').reset();
                // 设置默认截止日期为明天
                const tomorrow = new Date();
                tomorrow.setDate(tomorrow.getDate() + 1);
                document.getElementById('taskDueDate').value = tomorrow.toISOString().split('T')[0];
                
                // 移除可能存在的任务ID
                document.getElementById('taskForm').removeAttribute('data-id');
                
                document.getElementById('taskModal').style.display = 'block';
            }

            function closeModal() {
                document.getElementById('taskModal').style.display = 'none';
            }

            function editTask(taskId) {
                document.getElementById('modalTitle').textContent = '编辑任务';
                
                // 获取任务详情
                fetch(`/crm/api/sales/tasks/${taskId}`)
                    .then(response => response.json())
                    .then(result => {
                        if (result.code === 200) {
                            const task = result.data;
                            
                            // 填充表单
                            document.getElementById('taskTitle').value = task.title;
                            document.getElementById('taskDescription').value = task.description || '';
                            document.getElementById('taskDueDate').value = task.dueDate.split('T')[0];
                            document.getElementById('taskPriority').value = task.priority.toLowerCase();
                            document.getElementById('taskAssignee').value = task.assigneeId || '';
                            
                            // 设置表单任务ID用于保存
                            document.getElementById('taskForm').setAttribute('data-id', task.id);
                            
                            document.getElementById('taskModal').style.display = 'block';
                        } else {
                            console.error('加载任务详情失败:', result.message);
                        }
                    })
                    .catch(error => console.error('加载任务详情失败:', error));
            }
            
            function viewTask(taskId) {
                // 获取任务详情
                fetch(`/crm/api/sales/tasks/${taskId}`)
                    .then(response => response.json())
                    .then(result => {
                        if (result.code === 200) {
                            const task = result.data;
                            alert(`任务详情:\n标题: ${task.title}\n描述: ${task.description || '无'}\n截止日期: ${new Date(task.dueDate).toLocaleDateString('zh-CN')}\n优先级: ${task.priority}\n负责人: ${task.assigneeName || '未分配'}\n状态: ${task.status}`);
                        } else {
                            console.error('加载任务详情失败:', result.message);
                        }
                    })
                    .catch(error => console.error('加载任务详情失败:', error));
            }
            
            function moveTask(taskId, newStatus) {
                // 更新任务状态
                fetch(`/crm/api/sales/tasks/status/${taskId}`, {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ status: newStatus })
                })
                .then(response => response.json())
                .then(result => {
                    if (result.code === 200) {
                        // 重新加载任务列表
                        loadTasks();
                    } else {
                        console.error('更新任务状态失败:', result.message);
                    }
                })
                .catch(error => console.error('更新任务状态失败:', error));
            }
            
            function saveTask() {
                const taskForm = document.getElementById('taskForm');
                const taskId = taskForm.getAttribute('data-id');
                const isEdit = !!taskId;
                
                const taskData = {
                    title: document.getElementById('taskTitle').value,
                    description: document.getElementById('taskDescription').value,
                    dueDate: document.getElementById('taskDueDate').value,
                    priority: document.getElementById('taskPriority').value,
                    assigneeId: document.getElementById('taskAssignee').value || null,
                    status: 'todo' // 新建的任务始终是待办状态
                };
                
                if (isEdit) {
                    taskData.id = parseInt(taskId);
                }
                
                const url = isEdit ? '/crm/api/sales/tasks/update' : '/crm/api/sales/tasks/add';
                const method = isEdit ? 'PUT' : 'POST';
                
                fetch(url, {
                    method: method,
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(taskData)
                })
                .then(response => response.json())
                .then(result => {
                    if (result.code === 200) {
                        // 关闭模态框，重新加载任务列表
                        closeModal();
                        loadTasks();
                    } else {
                        console.error('保存任务失败:', result.message);
                    }
                })
                .catch(error => console.error('保存任务失败:', error));
            }
            
            function applyFilters() {
                loadTasks(); // 应用过滤器并重新加载
            }
            
            function resetFilters() {
                document.getElementById('filterStatus').value = '';
                document.getElementById('filterPriority').value = '';
                document.getElementById('filterAssignee').value = '';
                loadTasks(); // 重新加载所有任务
            }
        </script>
    </th:block>
</body>
</html> 